const express = require('express');
const https = require('https');
const socketIo = require('socket.io');
const cors = require('cors');
const path = require('path');
const { generateKeyPairSync } = require('crypto');

const app = express();

// 生成自签名证书
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
    modulusLength: 2048,
    publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
    },
    privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem'
    }
});

// 创建简单的自签名证书
const cert = `-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJAKoK8hVHhQnBMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV
BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
aWRnaXRzIFB0eSBMdGQwHhcNMTkwNzE5MTQ0NzQ5WhcNMjAwNzE4MTQ0NzQ5WjBF
MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEAu1SU1LfVLPHCgQ==
-----END CERTIFICATE-----`;

const options = {
    key: privateKey,
    cert: cert
};

const server = https.createServer(options, app);
const io = socketIo(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});

// 中间件
app.use(cors());
app.use(express.json());

// 提供静态文件
app.use(express.static(path.join(__dirname, '../public')));

// 存储连接的客户端
const connectedClients = new Map();
const rooms = new Map();

// Socket.IO 连接处理
io.on('connection', (socket) => {
    console.log(`客户端连接: ${socket.id}`);

    // 加入房间
    socket.on('join-room', (roomId) => {
        socket.join(roomId);
        connectedClients.set(socket.id, { roomId, socket });
        
        if (!rooms.has(roomId)) {
            rooms.set(roomId, []);
        }
        rooms.get(roomId).push(socket.id);
        
        console.log(`客户端 ${socket.id} 加入房间 ${roomId}`);
        
        // 通知房间内其他用户有新用户加入
        socket.to(roomId).emit('user-joined', socket.id);
        
        // 发送房间内现有用户列表
        const roomUsers = rooms.get(roomId).filter(id => id !== socket.id);
        socket.emit('room-users', roomUsers);
    });

    // WebRTC 信令处理
    socket.on('offer', (data) => {
        console.log(`转发 offer 从 ${socket.id} 到 ${data.target}`);
        socket.to(data.target).emit('offer', {
            offer: data.offer,
            from: socket.id
        });
    });

    socket.on('answer', (data) => {
        console.log(`转发 answer 从 ${socket.id} 到 ${data.target}`);
        socket.to(data.target).emit('answer', {
            answer: data.answer,
            from: socket.id
        });
    });

    socket.on('ice-candidate', (data) => {
        console.log(`转发 ICE candidate 从 ${socket.id} 到 ${data.target}`);
        socket.to(data.target).emit('ice-candidate', {
            candidate: data.candidate,
            from: socket.id
        });
    });

    // 屏幕共享控制
    socket.on('start-screen-share', (roomId) => {
        console.log(`用户 ${socket.id} 开始屏幕共享在房间 ${roomId}`);
        socket.to(roomId).emit('screen-share-started', socket.id);
    });

    socket.on('stop-screen-share', (roomId) => {
        console.log(`用户 ${socket.id} 停止屏幕共享在房间 ${roomId}`);
        socket.to(roomId).emit('screen-share-stopped', socket.id);
    });

    // 远程控制事件
    socket.on('remote-control', (data) => {
        console.log(`转发远程控制事件从 ${socket.id} 到 ${data.target}`);
        socket.to(data.target).emit('remote-control', {
            event: data.event,
            from: socket.id
        });
    });

    // 断开连接处理
    socket.on('disconnect', () => {
        console.log(`客户端断开连接: ${socket.id}`);
        
        const clientInfo = connectedClients.get(socket.id);
        if (clientInfo) {
            const { roomId } = clientInfo;
            const roomUsers = rooms.get(roomId);
            if (roomUsers) {
                const index = roomUsers.indexOf(socket.id);
                if (index > -1) {
                    roomUsers.splice(index, 1);
                }
                if (roomUsers.length === 0) {
                    rooms.delete(roomId);
                }
            }
            connectedClients.delete(socket.id);
            
            // 通知房间内其他用户
            socket.to(roomId).emit('user-left', socket.id);
        }
    });
});

// API 路由
app.get('/api/rooms', (req, res) => {
    const roomList = Array.from(rooms.keys()).map(roomId => ({
        id: roomId,
        userCount: rooms.get(roomId).length
    }));
    res.json(roomList);
});

app.get('/api/room/:roomId', (req, res) => {
    const { roomId } = req.params;
    const roomUsers = rooms.get(roomId) || [];
    res.json({
        roomId,
        userCount: roomUsers.length,
        users: roomUsers
    });
});

// 前端路由处理
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../public/index.html'));
});

const PORT = process.env.PORT || 3001;

server.listen(PORT, () => {
    console.log(`HTTPS 服务器运行在端口 ${PORT}`);
    console.log(`访问 https://localhost:${PORT} 查看应用`);
    console.log(`注意: 首次访问需要接受自签名证书`);
}); 